package com.zzl.ov_library.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzl.ov_library.dto.Result;
import com.zzl.ov_library.entity.Books;
import com.zzl.ov_library.entity.BorrowRecord;
import com.zzl.ov_library.entity.BorrowRecordVO;
import com.zzl.ov_library.entity.Inventory;
import com.zzl.ov_library.service.BooksService;
import com.zzl.ov_library.service.BorrowRecordService;
import com.zzl.ov_library.service.InventoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class BorrowRecordController {
    @Autowired
    private BorrowRecordService borrowRecordService;

    @Autowired
    private BooksService booksService;

    @Autowired
    private InventoryService inventoryService;

    //新增借阅记录
    @PostMapping("/borrowRecord/add")
    public Result addBorrowRecord(Integer userId, Integer bookId, Integer branchId) {
        //通过userId和bookId查询借阅记录是否已存在
        BorrowRecord borrowRecord = borrowRecordService.getOne(Wrappers.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId)
                .eq(BorrowRecord::getBookId, bookId)
                .orderByDesc(BorrowRecord::getBorrowTime)
                .last("limit 1"));
        if (borrowRecord != null && !borrowRecord.getStatus().equals("已还")) {
            return Result.fail().setMsg("已借阅本书");
        }

        BorrowRecord record = new BorrowRecord();
        record.setUserId(userId);
        record.setBookId(bookId);
        record.setBranchIdBorrow(branchId);

        LocalDate borrowDate = LocalDate.now();
        LocalDate dueDate = borrowDate.plusDays(30);

        record.setBorrowTime(java.sql.Date.valueOf(borrowDate));
        record.setDueTime(java.sql.Date.valueOf(dueDate));

        return borrowRecordService.save(record) ? Result.ok().setMsg("借阅成功") : Result.fail().setMsg("借阅失败");
    }

    //续借
    @PutMapping("/borrowRecord/renew/{recordId}")
    public Result renewBorrowRecord(@PathVariable Integer recordId) {
        BorrowRecord borrowRecord = borrowRecordService.getById(recordId);
        if (borrowRecord == null) {
            return Result.fail().setMsg("借阅记录不存在");
        }
        if (borrowRecord.getRenewCount() >= 1) {
            return Result.fail().setMsg("续借次数已达上限");
        }
        //获取原应还时间并转换为LocalDate，并增加30天
        LocalDate dueDate = borrowRecord.getDueTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate newDueDate = dueDate.plusDays(30);

        //设置新应还时间
        borrowRecord.setDueTime(java.sql.Date.valueOf(newDueDate));

        //增加续借次数
        borrowRecord.setRenewCount(borrowRecord.getRenewCount() + 1);

        return borrowRecordService.updateById(borrowRecord) ? Result.ok().setMsg("续借成功") : Result.fail().setMsg("续借失败");
    }

    //还书
    @PutMapping("/borrowRecord/return")
    public Result returnBorrowRecord(@RequestParam Integer recordId,@RequestParam Integer branchId) {
        BorrowRecord borrowRecord = borrowRecordService.getById(recordId);
        if (borrowRecord == null) {
            return Result.fail().setMsg("借阅记录不存在");
        }
        borrowRecord.setReturnTime(new java.sql.Date(System.currentTimeMillis()));
        borrowRecord.setBranchIdReturn(branchId);
        borrowRecord.setStatus("已还");
//        inventoryService.returnBook(branchId,borrowRecord.getBookId());

        Inventory inventory = inventoryService.getOne(Wrappers.lambdaQuery(Inventory.class)
                .eq(Inventory::getBranchId, branchId)
                .eq(Inventory::getBookId, borrowRecord.getBookId()));
        if (inventory != null){
            inventory.setAvailableCount(inventory.getAvailableCount()+1);
        }else {
            inventory = new Inventory();
            inventory.setBranchId(branchId);
            inventory.setBookId(borrowRecord.getBookId());
            inventory.setAvailableCount(1);
        }
        inventoryService.saveOrUpdate(inventory);

        return borrowRecordService.updateById(borrowRecord) ? Result.ok().setMsg("还书成功") : Result.fail().setMsg("还书失败");
    }

    //借阅信息列表
    @GetMapping("/borrowRecord/list")
    public Result list(@RequestParam(defaultValue = "1") Integer page,
                      @RequestParam(defaultValue = "10") Integer limit) {
        List<BorrowRecord> List = borrowRecordService.list(new Page<>(page,limit));
        long count = borrowRecordService.count();
        return Result.ok().setData(List).setCount(count).setMsg("查询成功");
    }

    //查询用户当前借阅
    @GetMapping("/borrowRecord/queryByUserId")
    public Result queryBorrowing(@RequestParam Integer userId) {
        System.out.println("userId:"+userId);
        List<BorrowRecord> recordList = borrowRecordService.list(Wrappers.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId));
        if (recordList.isEmpty())
            return Result.fail().setMsg("暂无借阅记录");
        List<BorrowRecordVO> borrowRecordVOList = new ArrayList<>();
        for (int i = 0; i < recordList.size(); i++) {
            BorrowRecordVO borrowRecordVO = new BorrowRecordVO();
            borrowRecordVO.setBookTitle(booksService.getById(recordList.get(i).getBookId()).getBookTitle());
            borrowRecordVO.setAuthor(booksService.getById(recordList.get(i).getBookId()).getAuthor());
            borrowRecordVO.setRecordId(recordList.get(i).getRecordId());
            borrowRecordVO.setUserId(recordList.get(i).getUserId());
            borrowRecordVO.setBookId(recordList.get(i).getBookId());
            borrowRecordVO.setBranchIdBorrow(recordList.get(i).getBranchIdBorrow());
            borrowRecordVO.setBorrowTime(recordList.get(i).getBorrowTime());
            borrowRecordVO.setDueTime(recordList.get(i).getDueTime());
            borrowRecordVO.setReturnTime(recordList.get(i).getReturnTime());
            borrowRecordVO.setRenewCount(recordList.get(i).getRenewCount());
            borrowRecordVO.setStatus(recordList.get(i).getStatus());
            borrowRecordVOList.add(borrowRecordVO);
        }
        System.out.println("borrowRecordVOList:"+borrowRecordVOList);
        return Result.ok().setData(borrowRecordVOList).setMsg("查询成功");
    }

    //查询用户正在借阅数量
    @GetMapping("/borrowRecord/queryBorrowingCount")
    public Result queryBorrowingCount(@RequestParam Integer userId) {
        List<BorrowRecord> recordList = borrowRecordService.list(Wrappers.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId)
                .eq(BorrowRecord::getStatus, "在借"));
        return Result.ok().setData(recordList.size()).setMsg("查询成功");
    }

    //查询用户逾期数量,逾期为逾期时间小于当前时间的借阅记录数量
    @GetMapping("/borrowRecord/queryOverdueCount")
    public Result queryOverdueCount(@RequestParam Integer userId) {
        int count = 0;
        List<BorrowRecord> recordList = borrowRecordService.list(Wrappers.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId)
                .eq(BorrowRecord::getStatus, "逾期"));
        count = recordList.size();
        recordList = borrowRecordService.list(Wrappers.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId)
                .eq(BorrowRecord::getStatus, "在借"));
        for (int i = 0; i < recordList.size(); i++) {
            if (recordList.get(i).getDueTime().before(new Date())) {
                //将该record的status设为逾期
                borrowRecordService.update(Wrappers.lambdaUpdate(BorrowRecord.class)
                        .eq(BorrowRecord::getRecordId, recordList.get(i).getRecordId())
                        .set(BorrowRecord::getStatus, "逾期"));
                count++;
            }
        }
        return Result.ok().setData(count).setMsg("查询成功");
    }

    //查询用户总借阅数
    @GetMapping("/borrowRecord/queryTotalCount")
    public Result queryTotalCount(@RequestParam Integer userId) {
        List<BorrowRecord> recordList = borrowRecordService.list(Wrappers.lambdaQuery(BorrowRecord.class)
                .eq(BorrowRecord::getUserId, userId));
        return Result.ok().setData(recordList.size()).setMsg("查询成功");
    }

}
